<?php
namespace Libraries;
/**
 * Des 加密类(可置顶是否base64)
 * created at 2016-05-07
 * @author 孙天相<suntianxiang@cjkt.com>
 * @package Libraries
 *
 */
class Des_base64
{   
    /**
     * @var bool $base64 是否base64
     */
    public $base64 = true;
    /**
     * @var string $key 密钥
     */
    public $key = '!&-join+';
    /**
     * 构造函数
     * @param string $key
     * @return Des_base64 加密类实例
     */
    public function __construct($key = FALSE){
        if($key){
            $this->key = $key;
        }
    }

    /**
     * 加密函数
     * @param $str 要加密的字符串
     * @param $key 密钥
     * @return string 加密串
     */
    public function encrypt($str)  
    {
        $key = $this->key;   
        $block = mcrypt_get_block_size('des', 'ecb');  
        
        $pad = $block - (strlen($str) % $block);  
        
        $str .= str_repeat(chr($pad), $pad);  
        
      
        $code = mcrypt_encrypt(MCRYPT_DES, $key, $str, MCRYPT_MODE_ECB);
        if($this->base64){
            $code = base64_encode($code);
        } 
        return $code;
    }
    /**
     * 解密函数
     * @param string $str 加密串
     * @return string 原文
     */
    public function decrypt($str)  
    {    
        $key = $this->key;  
        if($this->base64){
            $str = base64_decode($str);
        }
        $str = mcrypt_decrypt(MCRYPT_DES, $key, $str, MCRYPT_MODE_ECB);  
        
      
        
        $block = mcrypt_get_block_size('des', 'ecb');  
        
        $pad = ord($str[($len = strlen($str)) - 1]);  
        // var_dump($str);
        return substr($str, 0, strlen($str) - $pad);  
        
    }
    /**
     * 设置属性
     */
    public function __call($name , $arugment){
        if(!preg_match($preg, $name)){
            throw "invalid function";
        }

        if(count($argument) < 2){
            throw "invalid argument";
        }
        
        $key = str_replace('set', '', $name);
        $this->$key = $argument[0];
    }
}
?>